import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ConfigService } from '@nestjs/config';
import { BaseService } from '@wwjCommon/base/base.service';
import { CacheService } from '@wwjCommon/cache/cache.service';
import { LoggingService } from '@wwjCommon/logging/logging.service';
import { UploadService } from '@wwjVendor/upload/upload.service';
import { PayService } from '@wwjVendor/pay/pay.service';
import { SmsService } from '@wwjVendor/sms/sms.service';
import { NoticeService } from '@wwjVendor/notice/notice.service';

@Injectable()
export class BackupRecordsService extends BaseService<any> {
  private readonly logger = new Logger(BackupRecordsService.name);

  constructor(
    @InjectRepository(Object)
    protected readonly repository: Repository<any>,
    private readonly cacheService: CacheService,
    private readonly configService: ConfigService,
    private readonly loggingService: LoggingService,
    private readonly uploadService: UploadService,
    private readonly payService: PayService,
    private readonly smsService: SmsService,
    private readonly noticeService: NoticeService,
  ) {
    super(repository);
  }

  /**
   * add
   * 对应 PHP: BackupRecordsService_admin::add()
   * 逻辑类型: undefined - undefined
   */
  async add(data: any[]) {
    // 基于PHP真实逻辑: add
    // PHP原文: $data[ 'status' ] = BackupDict::STATUS_READY;         $data[ 'create_time' ] = time();         $res = $this->model->create($data);         return $res...
data[ 'status' ] = BackupDict.STATUS_READY;
        data[ 'create_time' ] = time(];
        const res = this.model.create(data);
        return res.id;
    }

    /**
     * 编辑备份记录
     * @param condition
     * @param data
     * @return true
     */
    async edit(condition, data)
    {
        this.model.where(condition).update(data);
        return true;
    }

    /**
     * 修改备注
     * @param params
     * @return true
     */
    async modifyRemark(params)
    {
        return this.edit([
            [ 'id', '=', params[ 'id' ] ]
        ], [ remark: params[ 'remark' ) )];
    }

    /**
     * 执行完成，更新备份记录的状态
     * @param backup_key
     * @return void
     */
    async complete(backup_key)
    {
        this.model.where([
            [ 'backup_key', '=', backup_key ),
        )).update([
            status: BackupDict.STATUS_COMPLETE,
            complete_time: time()
        ]];
    }

    /**
     * 执行失败，更新备份记录的状态
     * @param backup_key
     * @return void
     */
    async failed(backup_key)
    {
        const info = this.getInfo([
            [ 'backup_key', '=', backup_key )
        ), 'id,backup_key'];
        if (!!info)) {
            this.del(info[ 'id' )];
  }

  /**
   * edit
   * 对应 PHP: BackupRecordsService_admin::edit()
   * 逻辑类型: undefined - undefined
   */
  async edit(condition: any[], data: any[]) {
    // 基于PHP真实逻辑: edit
    // PHP原文: $this->model->where($condition)->update($data);         return true;     }      /**      * 修改备注      * @param $params      * @return true      */     ...
this.model.where(condition).update(data);
        return true;
    }

    /**
     * 修改备注
     * @param params
     * @return true
     */
    async modifyRemark(params)
    {
        return this.edit([
            [ 'id', '=', params[ 'id' ] ]
        ], [ remark: params[ 'remark' ) )];
    }

    /**
     * 执行完成，更新备份记录的状态
     * @param backup_key
     * @return void
     */
    async complete(backup_key)
    {
        this.model.where([
            [ 'backup_key', '=', backup_key ),
        )).update([
            status: BackupDict.STATUS_COMPLETE,
            complete_time: time()
        ]];
    }

    /**
     * 执行失败，更新备份记录的状态
     * @param backup_key
     * @return void
     */
    async failed(backup_key)
    {
        const info = this.getInfo([
            [ 'backup_key', '=', backup_key )
        ), 'id,backup_key'];
        if (!!info)) {
            this.del(info[ 'id' )];
  }

  /**
   * modifyRemark
   * 对应 PHP: BackupRecordsService_admin::modifyRemark()
   * 逻辑类型: undefined - undefined
   */
  async modifyRemark(params: any) {
    // 基于PHP真实逻辑: modifyRemark
    // PHP原文: return $this->edit([             [ 'id', '=', $params[ 'id' ] ]         ], [ 'remark' => $params[ 'remark' ] ]);     }      /**      * 执行完成，更新备份记录的状态 ...
return this.edit([
            [ 'id', '=', params[ 'id' ] ]
        ], [ remark: params[ 'remark' ) )];
    }

    /**
     * 执行完成，更新备份记录的状态
     * @param backup_key
     * @return void
     */
    async complete(backup_key)
    {
        this.model.where([
            [ 'backup_key', '=', backup_key ),
        )).update([
            status: BackupDict.STATUS_COMPLETE,
            complete_time: time()
        ]];
    }

    /**
     * 执行失败，更新备份记录的状态
     * @param backup_key
     * @return void
     */
    async failed(backup_key)
    {
        const info = this.getInfo([
            [ 'backup_key', '=', backup_key )
        ), 'id,backup_key'];
        if (!!info)) {
            this.del(info[ 'id' )];
  }

  /**
   * complete
   * 对应 PHP: BackupRecordsService_admin::complete()
   * 逻辑类型: undefined - undefined
   */
  async complete(backup_key: any) {
    // 基于PHP真实逻辑: complete
    // PHP原文: $this->model->where([             [ 'backup_key', '=', $backup_key ],         ])->update([             'status' => BackupDict::STATUS_COMPLETE,       ...
this.model.where([
            [ 'backup_key', '=', backup_key ),
        )).update([
            status: BackupDict.STATUS_COMPLETE,
            complete_time: time()
        ]];
    }

    /**
     * 执行失败，更新备份记录的状态
     * @param backup_key
     * @return void
     */
    async failed(backup_key)
    {
        const info = this.getInfo([
            [ 'backup_key', '=', backup_key )
        ), 'id,backup_key'];
        if (!!info)) {
            this.del(info[ 'id' )];
  }

  /**
   * failed
   * 对应 PHP: BackupRecordsService_admin::failed()
   * 逻辑类型: undefined - undefined
   */
  async failed(backup_key: any) {
    // 基于PHP真实逻辑: failed
    // PHP原文: $info = $this->getInfo([             [ 'backup_key', '=', $backup_key ]         ], 'id,backup_key');         if (!empty($info)) {             $this->d...
const info = this.getInfo([
            [ 'backup_key', '=', backup_key )
        ), 'id,backup_key'];
        if (!!info)) {
            this.del(info[ 'id' )];
  }

  /**
   * del
   * 对应 PHP: BackupRecordsService_admin::del()
   * 逻辑类型: undefined - undefined
   */
  async del(ids: any) {
    // 基于PHP真实逻辑: del
    // PHP原文: $list = $this->model->field('id,backup_key')->where([ [ 'id', 'in', $ids ] ])->select()->toArray();         if (empty($list)) {             throw new ...
const list = this.model.field('id,backup_key').where([ [ 'id', 'in', ids ) )).select().toArray(];
        if (!list)) {
            throw new AdminBusinessException('UPGRADE_RECORD_NOT_EXIST');
  }

  /**
   * checkDirExist
   * 对应 PHP: BackupRecordsService_admin::checkDirExist()
   * 逻辑类型: undefined - undefined
   */
  async checkDirExist(id: any) {
    // 基于PHP真实逻辑: checkDirExist
    // PHP原文: $field = 'id, version, backup_key';         $info = $this->model->where([             [ 'id', '=', $id ],             [ 'status', '=', BackupDict::STA...
const field = 'id, version, backup_key';
        const info = this.model.where([
            [ 'id', '=', id ],
            [ 'status', '=', BackupDict.STATUS_COMPLETE )
        )).field(field).append([ 'backup_dir', 'backup_code_dir', 'backup_sql_dir' )).findOrEmpty().toArray(];

        if (!info)) {
            throw new AdminBusinessException('UPGRADE_RECORD_NOT_EXIST');
  }

  /**
   * checkPermission
   * 对应 PHP: BackupRecordsService_admin::checkPermission()
   * 逻辑类型: undefined - undefined
   */
  async checkPermission() {
    // 基于PHP真实逻辑: checkPermission
    // PHP原文: $niucloud_dir = $this->root_path . 'niucloud' . DIRECTORY_SEPARATOR;         $upgrade_dir = $this->root_path . 'upgrade' . DIRECTORY_SEPARATOR;       ...
const niucloud_dir = this.root_path  + 'niucloud' . DIRECTORY_SEPARATOR;
        const upgrade_dir = this.root_path  + 'upgrade' . DIRECTORY_SEPARATOR;
        const admin_dir = this.root_path  + 'admin' . DIRECTORY_SEPARATOR;
        const web_dir = this.root_path  + 'web' . DIRECTORY_SEPARATOR;
        const wap_dir = this.root_path  + 'uni-app' . DIRECTORY_SEPARATOR;

        if (!is_dir(admin_dir)) throw new BusinessException('ADMIN_DIR_NOT_EXIST');
        if (!is_dir(web_dir)) throw new BusinessException('WEB_DIR_NOT_EXIST');
        if (!is_dir(wap_dir)) throw new BusinessException('UNIAPP_DIR_NOT_EXIST'];

        const data = [
            // 目录检测
            dir: [
                // 要求可读权限
                is_readable: [],
                // 要求可写权限
                is_write: []
            ]
        ];

        data[ 'dir' ][ 'is_readable' ][) = [ dir: str_replace(project_path(), '', niucloud_dir), status: is_readable(niucloud_dir) ];
        data[ 'dir' ][ 'is_readable' ][] = [ dir: str_replace(project_path(), '', upgrade_dir), status: is_readable(upgrade_dir) ];
        data[ 'dir' ][ 'is_readable' ][] = [ dir: str_replace(project_path(), '', admin_dir), status: is_readable(admin_dir) ];
        data[ 'dir' ][ 'is_readable' ][] = [ dir: str_replace(project_path(), '', web_dir), status: is_readable(web_dir) ];
        data[ 'dir' ][ 'is_readable' ][] = [ dir: str_replace(project_path(), '', wap_dir), status: is_readable(wap_dir) ];

        data[ 'dir' ][ 'is_write' ][] = [ dir: str_replace(project_path(), '', niucloud_dir), status: is_write(niucloud_dir) ];
        data[ 'dir' ][ 'is_write' ][] = [ dir: str_replace(project_path(), '', upgrade_dir), status: is_write(upgrade_dir) ];
        data[ 'dir' ][ 'is_write' ][] = [ dir: str_replace(project_path(), '', admin_dir), status: is_write(admin_dir) ];
        data[ 'dir' ][ 'is_write' ][] = [ dir: str_replace(project_path(), '', web_dir), status: is_write(web_dir) ];
        data[ 'dir' ][ 'is_write' ][] = [ dir: str_replace(project_path(), '', wap_dir), status: is_write(wap_dir) ];

        // 检测全部目录及文件是否可读可写，忽略指定目录

        // 忽略指定目录，admin
        const exclude_admin_dir = [ 'dist', 'node_modules', '.git' ];
        const check_res = checkDirPermissions(project_path()  + 'admin', [], exclude_admin_dir];

        // 忽略指定目录，uni-app
        const exclude_uniapp_dir = [ 'dist', 'node_modules', '.git' ];
        const check_res = array_merge2(check_res, checkDirPermissions(project_path()  + 'uni-app', [], exclude_uniapp_dir)];

        // 忽略指定目录，web
        const exclude_web_dir = [ '.nuxt', '.output', 'dist', 'node_modules', '.git' ];
        const check_res = array_merge2(check_res, checkDirPermissions(project_path()  + 'web', [], exclude_web_dir)];

        // 忽略指定目录，niucloud
        const exclude_niucloud_dir = [
            'public' . DIRECTORY_SEPARATOR  + 'admin',
            'public' . DIRECTORY_SEPARATOR  + 'wap',
            'public' . DIRECTORY_SEPARATOR  + 'web',
            'public' . DIRECTORY_SEPARATOR  + 'upload',
            'public' . DIRECTORY_SEPARATOR  + 'file',
            'runtime',
            'vendor',
            '.git'
        ];
        const check_res = array_merge2(check_res, checkDirPermissions(project_path()  + 'niucloud', [], exclude_niucloud_dir)];

        if (!!check_res[ 'unreadable' ))) {
            foreach (check_res[ 'unreadable' ) as item) {
                data[ 'dir' ][ 'is_readable' ][] = [ dir: str_replace(project_path(), '', item), status: false ];
            }
  }

  /**
   * restore
   * 对应 PHP: BackupRecordsService_admin::restore()
   * 逻辑类型: undefined - undefined
   */
  async restore(data: any) {
    // 基于PHP真实逻辑: restore
    // PHP原文: $field = 'id, version, backup_key';         $info = $this->model->where([             [ 'id', '=', $data[ 'id' ] ],             [ 'status', '=', Backu...
const field = 'id, version, backup_key';
        const info = this.model.where([
            [ 'id', '=', data[ 'id' ] ],
            [ 'status', '=', BackupDict.STATUS_COMPLETE )
        )).field(field).append([ 'backup_dir', 'backup_code_dir', 'backup_sql_dir' )).findOrEmpty().toArray(];

        if (!info)) {
            throw new AdminBusinessException('UPGRADE_RECORD_NOT_EXIST');
  }

  /**
   * manualBackup
   * 对应 PHP: BackupRecordsService_admin::manualBackup()
   * 逻辑类型: undefined - undefined
   */
  async manualBackup(data: any) {
    // 基于PHP真实逻辑: manualBackup
    // PHP原文: $res = [ 'code' => 1, 'data' => [], 'msg' => '' ];         $key = uniqid();         $cache_data = Cache::get($this->cache_key);         if ($cache_dat...
const res = [ code: 1, data: [], msg: '' ];
        const key = uniqid(];
        const cache_data = Cache.get(this.cache_key);
        if (cache_data) {
            const key = cache_data[ 'key' ];
  }

  /**
   * getRestoreTask
   * 对应 PHP: BackupRecordsService_admin::getRestoreTask()
   * 逻辑类型: undefined - undefined
   */
  async getRestoreTask() {
    // 基于PHP真实逻辑: getRestoreTask
    // PHP原文: $task_data = Cache::get($this->cache_restore_key) ?? [];         return $task_data;     }      /**      * 获取正在进行的备份任务      * @return mixed|null      *...
const task_data = Cache.get(this.cache_restore_key) || [];
        return task_data;
    }

    /**
     * 获取正在进行的备份任务
     * @return mixed|null
     */
    async getBackupTask()
    {
        const task_data = Cache.get(this.cache_key) || [];
        return task_data;
    }

    /**
     * 获取备份记录信息
     * @param condition
     * @param field
     * @return */
    async getInfo(condition, field = 'id, version, backup_key, content, status, fail_reason, create_time, complete_time')
    {
        return this.model.field(field).where(condition).findOrEmpty().toArray(];
    }

    /**
     * 备份记录列表
     * @param condition
     * @return * @throws \think\db\exception\DataNotFoundBusinessException
     * @throws \think\db\exception\DbBusinessException
     * @throws \think\db\exception\ModelNotFoundBusinessException
     */
    async getList(condition = [), field = 'id, version, backup_key, content, status, fail_reason, create_time, complete_time')
    {
        const order = "id desc";
        return this.model.where(condition).field(field).order(order).select().toArray(];
    }

    /**
     * 备份记录分页列表
     * @param where
     * @return */
    async getPage(where = [))
    {
        const field = 'id, version, backup_key, content, remark, complete_time';
        const order = "id desc";
        const search_model = this.model.where([
            [ 'status', '=', BackupDict.STATUS_COMPLETE ],
            [ 'content|version', 'like', '%' . where[ 'content' ]  + '%' )
        )).append([ 'backup_dir' )).field(field).order(order];
        return this.pageQuery(search_model);
    }

    /**
     * 备份代码
     * @param backup_key
     * @return void
     */
    async backupCode(backup_key)
    {
        const backup_dir = this.upgrade_dir . backup_key . DIRECTORY_SEPARATOR  + 'backup' . DIRECTORY_SEPARATOR  + 'code' . DIRECTORY_SEPARATOR;

        // 创建目录
        dir_mkdir(backup_dir);

        // 备份admin
        dir_copy(this.root_path  + 'admin', backup_dir  + 'admin', exclude_dirs: [ '.vscode', 'node_modules', 'dist' )];

        // 备份uni-app
        dir_copy(this.root_path  + 'uni-app', backup_dir  + 'uni-app', exclude_dirs: [ 'node_modules', 'dist' )];

        // 备份web
        dir_copy(this.root_path  + 'web', backup_dir  + 'web', exclude_dirs: [ 'node_modules', '.nuxt', '.output', 'dist' )];

        // 备份niucloud全部代码
        const niucloud_dir = backup_dir  + 'niucloud' . DIRECTORY_SEPARATOR;

        dir_copy(this.root_path  + 'niucloud', niucloud_dir, exclude_dirs: [ 'runtime', 'upload' ), exclude_files: ..user.ini];
        return true;
    }

    /**
     * 备份数据库
     * @param backup_key
     * @return void
     */
    async backupSql(backup_key)
    {
        const backup_dir = this.upgrade_dir . backup_key . DIRECTORY_SEPARATOR  + 'backup' . DIRECTORY_SEPARATOR  + 'sql' . DIRECTORY_SEPARATOR;
        // 创建目录
        dir_mkdir(backup_dir);

        const prefix = config('database.connections + ' . config('database.default'))[ 'prefix' ];

        // 不需要备份的表
        const not_need_backup = [
            "{prefix}sys_schedule_log",
            "{prefix}sys_user_log",
            "{prefix}jobs",
            "{prefix}jobs_failed",
            "{prefix}sys_upgrade_records",
            "{prefix}sys_backup_records"
        ];

        const db = new DbBackup(backup_dir, 1024 * 1024 * 2, not_need_backup, key: backup_key];

        const result = db.backupDatabaseSegment();
        if (result === true) return true;

        return db.getBackupProgress(;
  }
  }

  /**
   * getBackupTask
   * 对应 PHP: BackupRecordsService_admin::getBackupTask()
   * 逻辑类型: undefined - undefined
   */
  async getBackupTask() {
    // 基于PHP真实逻辑: getBackupTask
    // PHP原文: $task_data = Cache::get($this->cache_key) ?? [];         return $task_data;     }      /**      * 获取备份记录信息      * @param array $condition      * @para...
const task_data = Cache.get(this.cache_key) || [];
        return task_data;
    }

    /**
     * 获取备份记录信息
     * @param condition
     * @param field
     * @return */
    async getInfo(condition, field = 'id, version, backup_key, content, status, fail_reason, create_time, complete_time')
    {
        return this.model.field(field).where(condition).findOrEmpty().toArray(];
    }

    /**
     * 备份记录列表
     * @param condition
     * @return * @throws \think\db\exception\DataNotFoundBusinessException
     * @throws \think\db\exception\DbBusinessException
     * @throws \think\db\exception\ModelNotFoundBusinessException
     */
    async getList(condition = [), field = 'id, version, backup_key, content, status, fail_reason, create_time, complete_time')
    {
        const order = "id desc";
        return this.model.where(condition).field(field).order(order).select().toArray(];
    }

    /**
     * 备份记录分页列表
     * @param where
     * @return */
    async getPage(where = [))
    {
        const field = 'id, version, backup_key, content, remark, complete_time';
        const order = "id desc";
        const search_model = this.model.where([
            [ 'status', '=', BackupDict.STATUS_COMPLETE ],
            [ 'content|version', 'like', '%' . where[ 'content' ]  + '%' )
        )).append([ 'backup_dir' )).field(field).order(order];
        return this.pageQuery(search_model);
    }

    /**
     * 备份代码
     * @param backup_key
     * @return void
     */
    async backupCode(backup_key)
    {
        const backup_dir = this.upgrade_dir . backup_key . DIRECTORY_SEPARATOR  + 'backup' . DIRECTORY_SEPARATOR  + 'code' . DIRECTORY_SEPARATOR;

        // 创建目录
        dir_mkdir(backup_dir);

        // 备份admin
        dir_copy(this.root_path  + 'admin', backup_dir  + 'admin', exclude_dirs: [ '.vscode', 'node_modules', 'dist' )];

        // 备份uni-app
        dir_copy(this.root_path  + 'uni-app', backup_dir  + 'uni-app', exclude_dirs: [ 'node_modules', 'dist' )];

        // 备份web
        dir_copy(this.root_path  + 'web', backup_dir  + 'web', exclude_dirs: [ 'node_modules', '.nuxt', '.output', 'dist' )];

        // 备份niucloud全部代码
        const niucloud_dir = backup_dir  + 'niucloud' . DIRECTORY_SEPARATOR;

        dir_copy(this.root_path  + 'niucloud', niucloud_dir, exclude_dirs: [ 'runtime', 'upload' ), exclude_files: ..user.ini];
        return true;
    }

    /**
     * 备份数据库
     * @param backup_key
     * @return void
     */
    async backupSql(backup_key)
    {
        const backup_dir = this.upgrade_dir . backup_key . DIRECTORY_SEPARATOR  + 'backup' . DIRECTORY_SEPARATOR  + 'sql' . DIRECTORY_SEPARATOR;
        // 创建目录
        dir_mkdir(backup_dir);

        const prefix = config('database.connections + ' . config('database.default'))[ 'prefix' ];

        // 不需要备份的表
        const not_need_backup = [
            "{prefix}sys_schedule_log",
            "{prefix}sys_user_log",
            "{prefix}jobs",
            "{prefix}jobs_failed",
            "{prefix}sys_upgrade_records",
            "{prefix}sys_backup_records"
        ];

        const db = new DbBackup(backup_dir, 1024 * 1024 * 2, not_need_backup, key: backup_key];

        const result = db.backupDatabaseSegment();
        if (result === true) return true;

        return db.getBackupProgress(;
  }
  }

  /**
   * getInfo
   * 对应 PHP: BackupRecordsService_admin::getInfo()
   * 逻辑类型: undefined - undefined
   */
  async getInfo(condition: any[], field: any[]) {
    // 基于PHP真实逻辑: getInfo
    // PHP原文: return $this->model->field($field)->where($condition)->findOrEmpty()->toArray();     }      /**      * 备份记录列表      * @param $condition      * @return ...
return this.model.field(field).where(condition).findOrEmpty().toArray(];
    }

    /**
     * 备份记录列表
     * @param condition
     * @return * @throws \think\db\exception\DataNotFoundBusinessException
     * @throws \think\db\exception\DbBusinessException
     * @throws \think\db\exception\ModelNotFoundBusinessException
     */
    async getList(condition = [), field = 'id, version, backup_key, content, status, fail_reason, create_time, complete_time')
    {
        const order = "id desc";
        return this.model.where(condition).field(field).order(order).select().toArray(];
    }

    /**
     * 备份记录分页列表
     * @param where
     * @return */
    async getPage(where = [))
    {
        const field = 'id, version, backup_key, content, remark, complete_time';
        const order = "id desc";
        const search_model = this.model.where([
            [ 'status', '=', BackupDict.STATUS_COMPLETE ],
            [ 'content|version', 'like', '%' . where[ 'content' ]  + '%' )
        )).append([ 'backup_dir' )).field(field).order(order];
        return this.pageQuery(search_model);
    }

    /**
     * 备份代码
     * @param backup_key
     * @return void
     */
    async backupCode(backup_key)
    {
        const backup_dir = this.upgrade_dir . backup_key . DIRECTORY_SEPARATOR  + 'backup' . DIRECTORY_SEPARATOR  + 'code' . DIRECTORY_SEPARATOR;

        // 创建目录
        dir_mkdir(backup_dir);

        // 备份admin
        dir_copy(this.root_path  + 'admin', backup_dir  + 'admin', exclude_dirs: [ '.vscode', 'node_modules', 'dist' )];

        // 备份uni-app
        dir_copy(this.root_path  + 'uni-app', backup_dir  + 'uni-app', exclude_dirs: [ 'node_modules', 'dist' )];

        // 备份web
        dir_copy(this.root_path  + 'web', backup_dir  + 'web', exclude_dirs: [ 'node_modules', '.nuxt', '.output', 'dist' )];

        // 备份niucloud全部代码
        const niucloud_dir = backup_dir  + 'niucloud' . DIRECTORY_SEPARATOR;

        dir_copy(this.root_path  + 'niucloud', niucloud_dir, exclude_dirs: [ 'runtime', 'upload' ), exclude_files: ..user.ini];
        return true;
    }

    /**
     * 备份数据库
     * @param backup_key
     * @return void
     */
    async backupSql(backup_key)
    {
        const backup_dir = this.upgrade_dir . backup_key . DIRECTORY_SEPARATOR  + 'backup' . DIRECTORY_SEPARATOR  + 'sql' . DIRECTORY_SEPARATOR;
        // 创建目录
        dir_mkdir(backup_dir);

        const prefix = config('database.connections + ' . config('database.default'))[ 'prefix' ];

        // 不需要备份的表
        const not_need_backup = [
            "{prefix}sys_schedule_log",
            "{prefix}sys_user_log",
            "{prefix}jobs",
            "{prefix}jobs_failed",
            "{prefix}sys_upgrade_records",
            "{prefix}sys_backup_records"
        ];

        const db = new DbBackup(backup_dir, 1024 * 1024 * 2, not_need_backup, key: backup_key];

        const result = db.backupDatabaseSegment();
        if (result === true) return true;

        return db.getBackupProgress(;
  }
  }

  /**
   * getList
   * 对应 PHP: BackupRecordsService_admin::getList()
   * 逻辑类型: undefined - undefined
   */
  async getList(condition: any[], field: any[]) {
    // 基于PHP真实逻辑: getList
    // PHP原文: $order = "id desc";         return $this->model->where($condition)->field($field)->order($order)->select()->toArray();     }      /**      * 备份记录分页列表 ...
const order = "id desc";
        return this.model.where(condition).field(field).order(order).select().toArray(];
    }

    /**
     * 备份记录分页列表
     * @param where
     * @return */
    async getPage(where = [))
    {
        const field = 'id, version, backup_key, content, remark, complete_time';
        const order = "id desc";
        const search_model = this.model.where([
            [ 'status', '=', BackupDict.STATUS_COMPLETE ],
            [ 'content|version', 'like', '%' . where[ 'content' ]  + '%' )
        )).append([ 'backup_dir' )).field(field).order(order];
        return this.pageQuery(search_model);
    }

    /**
     * 备份代码
     * @param backup_key
     * @return void
     */
    async backupCode(backup_key)
    {
        const backup_dir = this.upgrade_dir . backup_key . DIRECTORY_SEPARATOR  + 'backup' . DIRECTORY_SEPARATOR  + 'code' . DIRECTORY_SEPARATOR;

        // 创建目录
        dir_mkdir(backup_dir);

        // 备份admin
        dir_copy(this.root_path  + 'admin', backup_dir  + 'admin', exclude_dirs: [ '.vscode', 'node_modules', 'dist' )];

        // 备份uni-app
        dir_copy(this.root_path  + 'uni-app', backup_dir  + 'uni-app', exclude_dirs: [ 'node_modules', 'dist' )];

        // 备份web
        dir_copy(this.root_path  + 'web', backup_dir  + 'web', exclude_dirs: [ 'node_modules', '.nuxt', '.output', 'dist' )];

        // 备份niucloud全部代码
        const niucloud_dir = backup_dir  + 'niucloud' . DIRECTORY_SEPARATOR;

        dir_copy(this.root_path  + 'niucloud', niucloud_dir, exclude_dirs: [ 'runtime', 'upload' ), exclude_files: ..user.ini];
        return true;
    }

    /**
     * 备份数据库
     * @param backup_key
     * @return void
     */
    async backupSql(backup_key)
    {
        const backup_dir = this.upgrade_dir . backup_key . DIRECTORY_SEPARATOR  + 'backup' . DIRECTORY_SEPARATOR  + 'sql' . DIRECTORY_SEPARATOR;
        // 创建目录
        dir_mkdir(backup_dir);

        const prefix = config('database.connections + ' . config('database.default'))[ 'prefix' ];

        // 不需要备份的表
        const not_need_backup = [
            "{prefix}sys_schedule_log",
            "{prefix}sys_user_log",
            "{prefix}jobs",
            "{prefix}jobs_failed",
            "{prefix}sys_upgrade_records",
            "{prefix}sys_backup_records"
        ];

        const db = new DbBackup(backup_dir, 1024 * 1024 * 2, not_need_backup, key: backup_key];

        const result = db.backupDatabaseSegment();
        if (result === true) return true;

        return db.getBackupProgress(;
  }
  }

  /**
   * getPage
   * 对应 PHP: BackupRecordsService_admin::getPage()
   * 逻辑类型: undefined - undefined
   */
  async getPage(where: any[]) {
    // 基于PHP真实逻辑: getPage
    // PHP原文: $field = 'id, version, backup_key, content, remark, complete_time';         $order = "id desc";         $search_model = $this->model->where([         ...
const field = 'id, version, backup_key, content, remark, complete_time';
        const order = "id desc";
        const search_model = this.model.where([
            [ 'status', '=', BackupDict.STATUS_COMPLETE ],
            [ 'content|version', 'like', '%' . where[ 'content' ]  + '%' )
        )).append([ 'backup_dir' )).field(field).order(order];
        return this.pageQuery(search_model);
    }

    /**
     * 备份代码
     * @param backup_key
     * @return void
     */
    async backupCode(backup_key)
    {
        const backup_dir = this.upgrade_dir . backup_key . DIRECTORY_SEPARATOR  + 'backup' . DIRECTORY_SEPARATOR  + 'code' . DIRECTORY_SEPARATOR;

        // 创建目录
        dir_mkdir(backup_dir);

        // 备份admin
        dir_copy(this.root_path  + 'admin', backup_dir  + 'admin', exclude_dirs: [ '.vscode', 'node_modules', 'dist' )];

        // 备份uni-app
        dir_copy(this.root_path  + 'uni-app', backup_dir  + 'uni-app', exclude_dirs: [ 'node_modules', 'dist' )];

        // 备份web
        dir_copy(this.root_path  + 'web', backup_dir  + 'web', exclude_dirs: [ 'node_modules', '.nuxt', '.output', 'dist' )];

        // 备份niucloud全部代码
        const niucloud_dir = backup_dir  + 'niucloud' . DIRECTORY_SEPARATOR;

        dir_copy(this.root_path  + 'niucloud', niucloud_dir, exclude_dirs: [ 'runtime', 'upload' ), exclude_files: ..user.ini];
        return true;
    }

    /**
     * 备份数据库
     * @param backup_key
     * @return void
     */
    async backupSql(backup_key)
    {
        const backup_dir = this.upgrade_dir . backup_key . DIRECTORY_SEPARATOR  + 'backup' . DIRECTORY_SEPARATOR  + 'sql' . DIRECTORY_SEPARATOR;
        // 创建目录
        dir_mkdir(backup_dir);

        const prefix = config('database.connections + ' . config('database.default'))[ 'prefix' ];

        // 不需要备份的表
        const not_need_backup = [
            "{prefix}sys_schedule_log",
            "{prefix}sys_user_log",
            "{prefix}jobs",
            "{prefix}jobs_failed",
            "{prefix}sys_upgrade_records",
            "{prefix}sys_backup_records"
        ];

        const db = new DbBackup(backup_dir, 1024 * 1024 * 2, not_need_backup, key: backup_key];

        const result = db.backupDatabaseSegment();
        if (result === true) return true;

        return db.getBackupProgress(;
  }
  }

  /**
   * backupCode
   * 对应 PHP: BackupRecordsService_admin::backupCode()
   * 逻辑类型: undefined - undefined
   */
  async backupCode(backup_key: any) {
    // 基于PHP真实逻辑: backupCode
    // PHP原文: $backup_dir = $this->upgrade_dir . $backup_key . DIRECTORY_SEPARATOR . 'backup' . DIRECTORY_SEPARATOR . 'code' . DIRECTORY_SEPARATOR;          // 创建目录...
const backup_dir = this.upgrade_dir . backup_key . DIRECTORY_SEPARATOR  + 'backup' . DIRECTORY_SEPARATOR  + 'code' . DIRECTORY_SEPARATOR;

        // 创建目录
        dir_mkdir(backup_dir);

        // 备份admin
        dir_copy(this.root_path  + 'admin', backup_dir  + 'admin', exclude_dirs: [ '.vscode', 'node_modules', 'dist' )];

        // 备份uni-app
        dir_copy(this.root_path  + 'uni-app', backup_dir  + 'uni-app', exclude_dirs: [ 'node_modules', 'dist' )];

        // 备份web
        dir_copy(this.root_path  + 'web', backup_dir  + 'web', exclude_dirs: [ 'node_modules', '.nuxt', '.output', 'dist' )];

        // 备份niucloud全部代码
        const niucloud_dir = backup_dir  + 'niucloud' . DIRECTORY_SEPARATOR;

        dir_copy(this.root_path  + 'niucloud', niucloud_dir, exclude_dirs: [ 'runtime', 'upload' ), exclude_files: ..user.ini];
        return true;
    }

    /**
     * 备份数据库
     * @param backup_key
     * @return void
     */
    async backupSql(backup_key)
    {
        const backup_dir = this.upgrade_dir . backup_key . DIRECTORY_SEPARATOR  + 'backup' . DIRECTORY_SEPARATOR  + 'sql' . DIRECTORY_SEPARATOR;
        // 创建目录
        dir_mkdir(backup_dir);

        const prefix = config('database.connections + ' . config('database.default'))[ 'prefix' ];

        // 不需要备份的表
        const not_need_backup = [
            "{prefix}sys_schedule_log",
            "{prefix}sys_user_log",
            "{prefix}jobs",
            "{prefix}jobs_failed",
            "{prefix}sys_upgrade_records",
            "{prefix}sys_backup_records"
        ];

        const db = new DbBackup(backup_dir, 1024 * 1024 * 2, not_need_backup, key: backup_key];

        const result = db.backupDatabaseSegment();
        if (result === true) return true;

        return db.getBackupProgress(;
  }
  }

  /**
   * backupSql
   * 对应 PHP: BackupRecordsService_admin::backupSql()
   * 逻辑类型: undefined - undefined
   */
  async backupSql(backup_key: any) {
    // 基于PHP真实逻辑: backupSql
    // PHP原文: $backup_dir = $this->upgrade_dir . $backup_key . DIRECTORY_SEPARATOR . 'backup' . DIRECTORY_SEPARATOR . 'sql' . DIRECTORY_SEPARATOR;         // 创建目录  ...
const backup_dir = this.upgrade_dir . backup_key . DIRECTORY_SEPARATOR  + 'backup' . DIRECTORY_SEPARATOR  + 'sql' . DIRECTORY_SEPARATOR;
        // 创建目录
        dir_mkdir(backup_dir);

        const prefix = config('database.connections + ' . config('database.default'))[ 'prefix' ];

        // 不需要备份的表
        const not_need_backup = [
            "{prefix}sys_schedule_log",
            "{prefix}sys_user_log",
            "{prefix}jobs",
            "{prefix}jobs_failed",
            "{prefix}sys_upgrade_records",
            "{prefix}sys_backup_records"
        ];

        const db = new DbBackup(backup_dir, 1024 * 1024 * 2, not_need_backup, key: backup_key];

        const result = db.backupDatabaseSegment();
        if (result === true) return true;

        return db.getBackupProgress(;
  }
  }
}
